#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import csv
import json
from datetime import datetime

class UserDatabase:
    def __init__(self, data_path='data'):
        """初始化用户数据库
        
        Args:
            data_path: 数据存储路径
        """
        self.data_path = data_path
        self.users_file = os.path.join(data_path, 'users.json')
        
        # 确保目录存在
        os.makedirs(data_path, exist_ok=True)
        
        self.users = self.load_users()
        
    def load_users(self):
        """加载用户数据
        
        Returns:
            dict: 用户数据字典
        """
        if os.path.exists(self.users_file):
            try:
                with open(self.users_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载用户数据失败: {str(e)}")
                return {}
        return {}
    
    def save_users(self):
        """保存用户数据"""
        try:
            with open(self.users_file, 'w', encoding='utf-8') as f:
                json.dump(self.users, f, ensure_ascii=False, indent=4)
            return True
        except Exception as e:
            print(f"保存用户数据失败: {str(e)}")
            return False
    
    def add_user(self, user_info):
        """添加新用户
        
        Args:
            user_info: 包含用户信息的字典，至少包含name字段
            
        Returns:
            bool: 是否添加成功
        """
        if not user_info or 'name' not in user_info:
            return False
            
        # 为新用户分配ID
        if not self.users:
            new_id = "1"
        else:
            try:
                ids = [int(id) for id in self.users.keys()]
                new_id = str(max(ids) + 1)
            except:
                new_id = "1"
        
        # 确保用户信息包含必要字段
        user_data = {
            'id': new_id,
            'name': user_info['name'],
            'student_id': user_info.get('student_id', ''),
            'department': user_info.get('department', ''),
            'register_time': user_info.get('register_time', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        }
        
        self.users[new_id] = user_data
        return self.save_users()
    
    def get_user(self, user_id):
        """获取用户信息
        
        Args:
            user_id: 用户ID
            
        Returns:
            dict: 用户信息
        """
        user = self.users.get(str(user_id))
        if user:
            # 确保ID字段包含在返回的用户对象中
            user['id'] = str(user_id)
        return user
    
    def get_user_by_id(self, user_id):
        """通过ID获取用户，与get_user相同，保持兼容性
        
        Args:
            user_id: 用户ID
            
        Returns:
            dict: 用户信息
        """
        return self.get_user(user_id)
    
    def get_user_by_name(self, name):
        """通过姓名查找用户
        
        Args:
            name: 用户姓名
            
        Returns:
            dict: 用户信息或None
        """
        for user_id, user_data in self.users.items():
            if user_data.get('name') == name:
                user_data['id'] = user_id
                return user_data
        return None
    
    def update_user(self, user_id, **kwargs):
        """更新用户信息
        
        Args:
            user_id: 用户ID
            **kwargs: 需要更新的字段
            
        Returns:
            bool: 是否更新成功
        """
        user_id = str(user_id)
        if user_id not in self.users:
            return False
            
        for key, value in kwargs.items():
            if key != 'id':  # 不允许更新ID
                self.users[user_id][key] = value
            
        return self.save_users()
    
    def delete_user(self, user_id):
        """删除用户
        
        Args:
            user_id: 用户ID
            
        Returns:
            bool: 是否删除成功
        """
        user_id = str(user_id)
        if user_id not in self.users:
            return False
            
        del self.users[user_id]
        return self.save_users()
    
    def get_all_users(self):
        """获取所有用户
        
        Returns:
            list: 所有用户信息列表
        """
        user_list = []
        for user_id, user_data in self.users.items():
            user = user_data.copy()
            user['id'] = user_id
            user_list.append(user)
        return user_list
    
    def search_users(self, keyword):
        """搜索用户
        
        Args:
            keyword: 搜索关键字(姓名、学号、部门)
            
        Returns:
            list: 符合条件的用户列表
        """
        keyword = keyword.lower()
        results = []
        
        for user_id, user_data in self.users.items():
            if (keyword in user_data.get('name', '').lower() or
                keyword in str(user_data.get('student_id', '')).lower() or
                keyword in str(user_data.get('department', '')).lower()):
                
                user = user_data.copy()
                user['id'] = user_id
                results.append(user)
                
        return results

    def get_attendance_records(self, date=None):
        """获取签到记录
        
        Args:
            date: 日期，格式为YYYY-MM-DD，如果为None则获取当天记录
            
        Returns:
            list: 签到记录列表
        """
        if date is None:
            date = datetime.now().strftime("%Y-%m-%d")
            
        attendance_dir = os.path.join(self.data_path, 'attendance')
        os.makedirs(attendance_dir, exist_ok=True)
        
        attendance_file = os.path.join(attendance_dir, f"{date}.csv")
        records = []
        
        if os.path.exists(attendance_file):
            try:
                with open(attendance_file, 'r', encoding='utf-8') as f:
                    reader = csv.reader(f)
                    next(reader, None)  # 跳过表头
                    for row in reader:
                        if len(row) >= 2:
                            records.append({
                                'name': row[0],
                                'time': row[1]
                            })
            except Exception as e:
                print(f"读取签到记录失败: {str(e)}")
        
        return records 